package org.example.short_link.admin.service.ServiceImpl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.example.short_link.admin.common.convention.Exception.ClientException;
import org.example.short_link.admin.dao.entity.UserDO;
import org.example.short_link.admin.dao.mapper.UserMapper;
import org.example.short_link.admin.dto.req.UserLoginReqDTO;
import org.example.short_link.admin.dto.req.UserRegisterReqDTO;
import org.example.short_link.admin.dto.req.UserUpdateReqDTO;
import org.example.short_link.admin.dto.resp.UserLoginRespDTO;
import org.example.short_link.admin.dto.resp.UserRespDTO;
import org.example.short_link.admin.service.GroupService;
import org.example.short_link.admin.service.UserService;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static org.example.short_link.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;
import static org.example.short_link.admin.common.enums.UserErrorCdeEnum.*;


/**
 * 用户接口实现类
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;

    private final RedissonClient redissonClient;

    private final StringRedisTemplate  stringRedisTemplate;

    private final GroupService groupService;

    /**
     * 根据用户查询用户信息接口
     * @param username 用户名
     * @return
     */
    @Override
    public UserRespDTO getUserByUsername(String username) {
        LambdaQueryWrapper<UserDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserDO::getUsername , username);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        UserRespDTO result = new UserRespDTO();

        if(userDO == null){
            throw new ClientException(USER_NULL);
        }else{
            BeanUtils.copyProperties(userDO,result);
            return result;
        }

    }

    /**
     * 用户查询接口
     * @param username 用户名
     * @return
     */
    @Override
    public Boolean hsUserName(String username) {
        //使用布隆过滤器判断是否存在用户名
        return !userRegisterCachePenetrationBloomFilter.contains(username);


    }

    /**
     * 用户注册接口
     * @param requestParam 注册用户请求参数
     */
    @Override
    public void register(UserRegisterReqDTO requestParam) {
        if(!hsUserName(requestParam.getUsername())){
            throw new ClientException(USER_NAME_EXIST);
        }

        RLock lock = redissonClient.getLock(LOCK_USER_REGISTER_KEY + requestParam.getUsername());
        try {
            if(lock.tryLock()){
                try {
                    int insert = baseMapper.insert(BeanUtil.toBean(requestParam, UserDO.class));
                    if(insert < 1){
                        //如果插入成功返回1 不成功返回0
                        throw new ClientException(USER_SAVE_ERROR);
                    }
                }catch (DuplicateKeyException ex){
                    throw new ClientException(USER_EXIST);
                }
                //想法是 只要当前这个用户获取到这个锁 那么意思是 只要获取到这个锁 就能注册成功
                //将注册用户的用户名加入到布隆过滤器中
                userRegisterCachePenetrationBloomFilter.add(requestParam.getUsername());

                //创建用户的时候 添加一个默认分组
                groupService.SaveGroup(requestParam.getUsername(),"默认分组");
                return;

            }
            throw new ClientException(USER_NAME_EXIST);

        }finally {
            lock.unlock();
        }
    }
    /**
     * 修改用户接口
     * @param requestParam
     */
    @Override
    public void update(UserUpdateReqDTO requestParam) {

        //是因为我们的分表是基于用户名，所以我们可以根据用户名来eq
        // TODO : 验证当前用户名是否为登录用户？
        LambdaQueryWrapper<UserDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserDO::getUsername,requestParam.getUsername());
        baseMapper.update(BeanUtil.toBean(requestParam,UserDO.class),queryWrapper);
    }

    /**
     * 用户登录
     * @param requestParam
     * @return
     */
    @Override
    public UserLoginRespDTO login(@RequestBody UserLoginReqDTO requestParam) {
        LambdaQueryWrapper<UserDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserDO::getUsername , requestParam.getUsername())
                .eq(UserDO::getPassword,requestParam.getPassword())
                .eq(UserDO::getDelFlag , 0);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if(userDO == null){
            throw new ClientException("用户不存在");
        }
        Boolean hasLogin = stringRedisTemplate.hasKey("login_" + requestParam.getUsername());
        if(hasLogin != null && hasLogin){
            throw new ClientException("用户已登录");
        }

        /**
         * 防止重复登录设计思路
         * Hash
         * Key : login_用户名
         * Value：
         *  Key：token标识
         *  Val：JSON 字符串（用户信息）
         */

        String uuid = UUID.randomUUID().toString();
        //Map<String, Object> userInfoMap = new HashMap<>();
        stringRedisTemplate.opsForHash().put("login_"+requestParam.getUsername(),uuid,JSON.toJSONString(userDO));
        stringRedisTemplate.expire("login_"+requestParam.getUsername(),30L,TimeUnit.DAYS);
        return new UserLoginRespDTO(uuid);
    }

    /**
     * 查询用户是否登录
     * @param username 用户名
     * @param token 用户登录凭证
     * @return
     */
    @Override
    public Boolean checkLogin(String username , String token) {

      return stringRedisTemplate.opsForHash().get("login_"+username ,token) != null;

    }

    /**
     * 用户退出
     * @param username 用户名
     * @param token 用户登录凭证
     */
    @Override
    public void logout(String username, String token) {
        // 要先登录 才能 退出
        if(checkLogin(username,token)){
            stringRedisTemplate.delete("login_"+username);
            return;
        }
        throw new ClientException("用户Token不存在或用户未登录");
    }


}
